package com.ssm.sport.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.sport.dto.ResultDTO;
import com.ssm.sport.entity.Category;
import com.ssm.sport.entity.Product;
import com.ssm.sport.service.CategoryService;
import com.ssm.sport.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品控制器
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取热门商品
     */
    @GetMapping("/hot")
    @ResponseBody
    public ResultDTO<?> getHotProducts(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 6; // 默认展示6条热门商品
        }
        List<Product> hotProducts = productService.getHotProducts(limit);
        for (Product hotProduct : hotProducts) {
            hotProduct.setMainImage("/sport_mall_war"+hotProduct.getMainImage());
        }
        return ResultDTO.success(hotProducts);
    }

    /**
     * 获取新品
     */
    @GetMapping("/new")
    @ResponseBody
    public ResultDTO<?> getNewProducts(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 6; // 默认展示6条新品
        }
        List<Product> newProducts = productService.getNewProducts(limit);
        return ResultDTO.success(newProducts);
    }

    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public String searchProducts(String keyword, Integer pageNum, Integer pageSize, Model model) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 12;
        }
        
        // 获取所有一级分类，用于导航栏
        List<Category> categories = categoryService.getTopCategories();
        model.addAttribute("categories", categories);
        
        // 搜索商品
        Page<Product> page = new Page<>(pageNum, pageSize);
        IPage<Product> productPage = productService.searchProducts(keyword, page);
        
        model.addAttribute("keyword", keyword);
        model.addAttribute("products", productPage.getRecords());
        model.addAttribute("total", productPage.getTotal());
        model.addAttribute("pages", productPage.getPages());
        model.addAttribute("pageNum", productPage.getCurrent());
        model.addAttribute("pageSize", productPage.getSize());
        
        return "product_list";
    }
    
    /**
     * 搜索商品API
     */
    @GetMapping("/api/search")
    @ResponseBody
    public ResultDTO<?> searchProductsApi(String keyword, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 12;
        }
        
        Page<Product> page = new Page<>(pageNum, pageSize);
        IPage<Product> productPage = productService.searchProducts(keyword, page);
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", productPage.getTotal());
        result.put("pages", productPage.getPages());
        result.put("pageNum", productPage.getCurrent());
        result.put("pageSize", productPage.getSize());
        result.put("list", productPage.getRecords());
        
        return ResultDTO.success(result);
    }

    /**
     * 获取商品详情（API接口）
     */
    @GetMapping("/api/detail/{id}")
    @ResponseBody
    public ResultDTO<?> getProductDetail(@PathVariable Integer id) {
        if (id == null || id <= 0) {
            return ResultDTO.failure("商品ID不合法");
        }
        
        Product product = productService.getById(id);
        if (product == null || product.getStatus() != 1) {
            return ResultDTO.failure("商品不存在或已下架");
        }
        
        return ResultDTO.success(product);
    }
    
    /**
     * 商品详情页面
     */
    @GetMapping("/detail/{id}")
    public String productDetailPage(@PathVariable Integer id, Model model) {
        // 获取所有一级分类，用于导航栏
        List<Category> categories = categoryService.getTopCategories();
        model.addAttribute("categories", categories);
        
        // 获取商品详情
        Product product = productService.getById(id);
        if (product == null || product.getStatus() != 1) {
            return "error/404"; // 商品不存在或已下架，返回404页面
        }
        product.setMainImage("/sport_mall_war"+product.getMainImage());
        model.addAttribute("product", product);
        
        // 获取相关商品推荐
        List<Product> relatedProducts = productService.getRelatedProducts(id, product.getCategoryId(), 4);
        model.addAttribute("relatedProducts", relatedProducts);
        
        return "product_detail";
    }

    /**
     * 根据分类获取商品列表页面
     */
    @GetMapping("/category/{categoryId}")
    public String getProductsByCategoryPage(@PathVariable Integer categoryId, Model model) {
        if (categoryId == null || categoryId <= 0) {
            return "error/404";
        }
        
        // 获取所有一级分类，用于导航栏
        List<Category> categories = categoryService.getTopCategories();
        model.addAttribute("categories", categories);
        
        // 获取当前分类信息
        Category category = categoryService.getById(categoryId);
        if (category == null) {
            return "error/404";
        }
        
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("categoryName", category.getName());
        
        // 获取分类下的商品（第一页）
        Page<Product> page = new Page<>(1, 12);
        IPage<Product> productPage = productService.getProductsByCategory(categoryId, page);
        if (productPage.getSize() > 0) {
            for (Product product : productPage.getRecords()) {
                product.setMainImage("/sport_mall_war" + product.getMainImage());
            }
        }
        
        model.addAttribute("products", productPage.getRecords());
        model.addAttribute("total", productPage.getTotal());
        model.addAttribute("pages", productPage.getPages());
        model.addAttribute("pageNum", productPage.getCurrent());
        model.addAttribute("pageSize", productPage.getSize());
        
        return "product_list";
    }
    
    /**
     * 根据分类获取商品列表（API接口）
     */
    @GetMapping("/api/category/{categoryId}")
    @ResponseBody
    public ResultDTO<?> getProductsByCategoryApi(@PathVariable Integer categoryId, Integer pageNum, Integer pageSize, String sort) {
        if (categoryId == null || categoryId <= 0) {
            return ResultDTO.failure("分类ID不合法");
        }
        
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 12;
        }
        
        Page<Product> page = new Page<>(pageNum, pageSize);
        IPage<Product> productPage = productService.getProductsByCategory(categoryId, page, sort);
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", productPage.getTotal());
        result.put("pages", productPage.getPages());
        result.put("pageNum", productPage.getCurrent());
        result.put("pageSize", productPage.getSize());
        result.put("list", productPage.getRecords());
        
        return ResultDTO.success(result);
    }
} 